import random
import string
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, Request
from sqlalchemy.ext.asyncio import AsyncSession
from redis import Redis

from config.env import JwtConfig
from config.get_db import get_db
from module_admin.entity.vo.email_vo import EmailCodeRequest, EmailCheckRequest, ResetPasswordRequest, EmailLoginRequest
from module_admin.entity.vo.login_vo import EmailUserRegister
from module_admin.service.email_service import EmailService
from module_admin.service.login_service import LoginService
from module_admin.entity.vo.login_vo import Token
from utils.response_util import ResponseUtil
from datetime import timedelta
import uuid

emailController = APIRouter(prefix="/email")


@emailController.post("/auth/send-email-code", summary="发送邮箱验证码")
async def send_email_code(
    request: Request, 
    email_request: EmailCodeRequest, 
    query_db: AsyncSession = Depends(get_db)
):
    """
    发送邮箱验证码
    """
    result = await EmailService.send_email_code(request, email_request, query_db)
    return ResponseUtil.success(data=result, msg="验证码发送成功")


@emailController.post("/auth/check-email", summary="检查邮箱是否存在")
async def check_email_exists(
    request: Request,
    email_check: EmailCheckRequest,
    query_db: AsyncSession = Depends(get_db)
):
    """
    检查邮箱是否已注册
    """
    result = await EmailService.check_email_exists(query_db, email_check.email)
    return ResponseUtil.success(data={"exists": result}, msg="检查完成")



@emailController.post("/auth/reset-password", summary="重置密码")
async def reset_password(
    request: Request,
    reset_request: ResetPasswordRequest,
    query_db: AsyncSession = Depends(get_db)
):
    """
    通过邮箱验证码重置密码
    """
    result = await EmailService.reset_password(request, reset_request, query_db)
    return ResponseUtil.success(data=result, msg="密码重置成功")


@emailController.post("/auth/register", summary="邮箱注册")
async def register_with_email(
    request: Request,
    register_request: EmailUserRegister,
    query_db: AsyncSession = Depends(get_db)
):
    """
    通过邮箱验证码注册用户
    """
    result = await EmailService.register_with_email(request, register_request, query_db)
    return ResponseUtil.success(data=result, msg="注册成功")


@emailController.post("/auth/login", summary="邮箱登录", response_model=Token)
async def login_with_email(
    request: Request,
    email_login: EmailLoginRequest,
    query_db: AsyncSession = Depends(get_db)
):
    """
    通过邮箱密码登录
    """
    result = await LoginService.authenticate_user_by_email(request, query_db, email_login.email, email_login.password)
    access_token_expires = timedelta(minutes=JwtConfig.jwt_expire_minutes)
    session_id = str(uuid.uuid4())
    access_token = await LoginService.create_access_token(
        data={
            'user_id': str(result[0].user_id),
            'user_name': result[0].user_name,
            'dept_name': result[1].dept_name if result[1] else None,
            'session_id': session_id,
        },
        expires_delta=access_token_expires,
    )

    # 保存token到Redis
    await request.app.state.redis.set(
        f'access_token:{session_id}',
        access_token,
        ex=timedelta(minutes=JwtConfig.jwt_expire_minutes),
    )

    return ResponseUtil.success(data={
        "access_token": access_token,
        "token_type": "bearer"
    }, msg="登录成功")

